<template>
    <div class="users">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card class="box-card">
            <el-row :gutter="12">
                <el-col :span="8">
                    <el-input v-model="pageFn.page.query">
                        <template #append>
                            <el-button icon="el-icon-search" @click="btns" ></el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="pageFn.addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="pageFn.usersData" border style="width: 100%" class="table">
                <el-table-column type="index" width="50" />
                <el-table-column prop="username" label="姓名" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="mobile" label="电话" />
                <el-table-column prop="create_time" label="创建日期" />
                <el-table-column prop="mg_state" label="用户状态">
                    <template v-slot="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="userChangeStatusFn(scope.row)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="操作">
                    <template v-slot="scope">
                        <!-- 编辑按钮 -->
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            circle
                            size="mini"
                            @click="editDialog(scope.row)"
                        ></el-button>
                        <!-- 分配角色 -->
                        <el-button
                            type="success"
                            icon="el-icon-check"
                            circle
                            size="mini"
                            @click="deliverDialog(scope.row)"
                        ></el-button>
                        <!-- 删除按钮 -->
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            circle
                            size="mini"
                            @click="deleteDialog(scope.row.id)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <!-- page-sizes每页显示个数选择器的的选项设置 -->
            <el-pagination
                v-model:currentPage="currentPage4"
                :page-sizes="[1, 3, 5, 7]"
                :page-size="Number(pageFn.page.pagesize)"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageFn.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            ></el-pagination>

            <!-- 添加用户的对话框 -->
            <el-dialog v-model="pageFn.addDialogVisible" title="添加用户" width="40%">
                <el-form
                    ref="addFormRef"
                    :model="pageFn.addForm"
                    :rules="pageFn.addFormRules"
                    label-width="80px"
                >
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="pageFn.addForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="pageFn.addForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="pageFn.addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="mobile">
                        <el-input v-model="pageFn.addForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="pageFn.addDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="addUsersFn">确定</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 编辑用户的对话框 -->
            <el-dialog v-model="pageFn.editDialogVisible" title="编辑用户" width="40%">
                <el-form ref="editFormRef" :model="pageFn.editForm" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="pageFn.editForm.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="pageFn.editForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="mobile">
                        <el-input v-model="pageFn.editForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="pageFn.editDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="editUsersFn">确定</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 分配角色的对话框 -->
            <el-dialog v-model="pageFn.deliverDialogVisible" title="编辑角色" width="40%">
                <el-form ref="deliverFormRef" :model="pageFn.deliverForm" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="pageFn.deliverForm.username" disabled></el-input>
                    </el-form-item>
                    <!-- 请选择 -->
                    <el-form-item label="角色" label-width="80px">
                        <el-select v-model="pageFn.deliverForm.rid" placeholder="请选择">
                            <el-option label="请选择" disabled :value="-1"></el-option>
                            <el-option
                                v-for="item in pageFn.roleList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="pageFn.deliverDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="deliverUsers">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
import { reactive, ref } from 'vue'
import { getUsers, addUsers, changeUserStatus, submitEdidUserInfo, deleteUser, getRoles, getUsersByID,assignRoles } from '../../http/api'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

export default {
    setup() {



        const router =useRouter()
        const route =useRoute()
        let pageFn = reactive({
            bySearch:false,
            page: {
                // 页数发生改变时触发
                pagenum:route.query.pagenum || 1,
                // 每页显示条目个数
                pagesize:route.query.pagesize || 7,
                query:route.query.query
            },
            // 用户列表的数据
            usersData: [],
            // 用户状态的开关
            value: true,
            total: '',
            addDialogVisible: false,
            // 添加用户的表单数据
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // 添加用户的验证规则
            addFormRules: {
                username: [
                    {
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur',
                    },
                ],
                password: [
                    {
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur',
                    }
                ],
                email: [{
                    required: true,
                    message: '请输入邮箱',
                    trigger: 'blur'
                }, {
                    type: 'email',
                    message: '请输入正确的邮箱地址',
                    trigger: ['blur', 'change']
                }

                ]
            },
            // 编辑用户的表单数据
            editForm: {
                username: '',
                id: '',
                email: '',
                mobile: ''
            },
            // 编辑用户的显示与隐藏
            editDialogVisible: false,
            // 编辑角色的显示与隐藏
            deliverDialogVisible: false,
            // 编辑角色的表单数据
            deliverForm: {
                username: '',
                id: '',
                rid: ''
            },
            roleList: [],
        })

        
        function btns(){
            pageFn.bySearch = true
            router.push({
                query:Object.assign({},route.query,{
                    query:pageFn.page.query
                })
            }).catch(r=>console.log("继续"))
            getUsersFn()
        }
        let getUsersFn = async () => {
            let res = await getUsers(pageFn.page)
            // console.log(res);
            pageFn.usersData = res.users
            pageFn.total = res.total
            // console.log(pageFn.usersData);
        }

        // 每页条数（pagesize）发生改变时触发
        let handleSizeChange = (num) => {
            console.log(num);
            
            pageFn.page.pagesize = num
            router.push({
                query:Object.assign({},route.query,{
                    pagesize:pageFn.page.pagesize
                })
            }).catch(r=>console.log("继续"))
            getUsersFn()
        }

        // 页数发生改变时触发
        let handleCurrentChange = (num) => {
            console.log(num);
            pageFn.page.pagenum = num

            router.push({
                query:Object.assign({},route.query,{
                    pagenum:pageFn.page.pagenum
                })
            }).catch(r=>console.log("继续"))
            getUsersFn()
        }

        let addFormRef = ref(null)

        // 点击按钮,添加新用户
        let addUsersFn = () => {
            // console.log(addFormRef.value);
            addFormRef.value.validate(async valid => {
                if (!valid) return
                await addUsers(pageFn.addForm)
                pageFn.addDialogVisible = false
                addFormRef.value.resetFields()
                getUsersFn()
            })
        }

        // 修改用户状态
        let userChangeStatusFn = async (row) => {
            // console.log(row);
            await changeUserStatus(row.id, row.mg_state)
            getUsersFn()
        }

        // 展示编辑用户的对话框
        let editDialog = (row) => {
            // console.log(row);
            pageFn.editForm = { ...row }
            pageFn.editDialogVisible = true
        }

        // 编辑用户，并提交
        let editUsersFn = async (row) => {
            console.log(row);
            const { id, email, mobile } = pageFn.editForm
            await submitEdidUserInfo(id, pageFn.editForm)
            pageFn.editDialogVisible = false
            getUsersFn()
        }

        // 分配角色
        let deliverDialog = async (row) => {
            console.log(row);
            // pageFn.deliverForm = { ...row }
            const { id, username, role_name } = row;
            pageFn.deliverDialogVisible = true
            // { rid }这样写是因为返回的是对象
            const { rid } = await getUsersByID(id)
            console.log(rid);
            pageFn.deliverForm.id = id;
            pageFn.deliverForm.username = username;
            pageFn.deliverForm.role_name = role_name;
            pageFn.deliverForm.rid = rid;
            // 获取角色列表数据
            const res = await getRoles();
            pageFn.roleList = res;
            console.log(pageFn.roleList);
        }

        // 分配角色提交
        let deliverUsers = async () => {
            const { id, rid } = pageFn.deliverForm
            await assignRoles(id, rid)

            pageFn.deliverDialogVisible = false
            getUsersFn()
        }

        // 删除用户
        let deleteDialog = (id) => {
            console.log(id);
            ElMessageBox.confirm(
                '此操作将永久删除该文件, 是否继续?', '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(async () => {
                    await deleteUser(id)
                    getUsersFn()
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        }

        // 通过搜索获取用户列表
       
        getUsersFn()

        return {
            pageFn,
            handleSizeChange,
            handleCurrentChange,
            addUsersFn,
            addFormRef,
            userChangeStatusFn,
            editDialog,
            editUsersFn,
            deleteDialog,
            deliverDialog,
            deliverUsers,
            btns
        }
    }
}
</script>

<style lang="scss" scoped>
.users {
    background-color: #fff;
    border-radius: 4px;
    padding: 15px;
}

.box-card {
    margin: 15px;
}

.table {
    margin-top: 20px;
}
</style>